﻿using Interface.Utility.Helper;
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Linq;
using System.Text;

namespace Interface.Core.Utility
{
    public static class CredentialUtility
    {
        private static DateTime baseTime = new DateTime(1970, 1, 1);
        private static readonly XmlDocument xml = null;

        static CredentialUtility()
        {
            string path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"\partner.config";

            using (StreamReader sr = new StreamReader(path))
            {
                xml = new XmlDocument(); xml.LoadXml(sr.ReadToEnd());
            }
        }

        private static long GetLongByDateTime(DateTime time)
        {
            return (time.Ticks - baseTime.Ticks) / 10000000 - 8 * 60 * 60;
        }

        public static bool Validate(string appid, string token, string timestamp)
        {
            long time = 0, server = GetLongByDateTime(DateTime.Now);

            if (!long.TryParse(timestamp, out time)) { return false; }

            if (Math.Abs(time - server) > 300) { return false; }

            XmlNode node = xml.SelectSingleNode(string.Format(@"//node[@appID='{0}']", appid));

            if (node != null)
            {
                XmlAttribute attribute = node.Attributes["appSecret"];

                if (attribute != null && !string.IsNullOrEmpty(attribute.Value))
                {
                    return EncryptHelper.EncryptSHA1(attribute.Value + timestamp).Equals(token);
                }
            }

            return false;
        }
    }
}